// 1. React核心库
import React, { useState, useRef, useCallback } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, message, Modal, Space, Tag, Popconfirm } from 'antd';

// 3. 图标库
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable, ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 工具库
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { AIModel, AIModelRequest } from '@/services/generated';

const AIModelList: React.FC = () => {
  const [currentRecord, setCurrentRecord] = useState<AIModel | null>(null);
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);

  // 删除模型
  const handleDelete = useCallback(async (id: number) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await apiClients.aiChat.aiChatModelsDestroy({ id: String(id) });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 表格列定义
  const columns: ProColumns<AIModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
      sorter: true,
    },
    {
      title: '模型名称',
      dataIndex: 'name',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '模型代码',
      dataIndex: 'model_code',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '提供商',
      dataIndex: 'provider_name',
      search: false,
      render: (_, record) => (
        <Tag color="blue">{record.provider_name || '未设置'}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      valueType: 'select',
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
      render: (_, record) => (
        <Tag color={record.is_active ? 'green' : 'red'}>
          {record.is_active ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '最大Token',
      dataIndex: 'max_tokens',
      search: false,
      render: (value) => (
        <Tag color="purple">{value?.toLocaleString() || 0}</Tag>
      ),
    },
    {
      title: '每1k Token成本',
      dataIndex: 'cost_per_1k_tokens',
      search: false,
      render: (value) => `$${Number(value || 0).toFixed(6)}`,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      render: (_, record) => {
        if (!record.created_at) return '-';
        const date = dayjs(record.created_at);
        return date.isValid() ? date.format('MM-DD HH:mm') : '-';
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            href={`/ai-chat/models/detail/${record.id}`}
          >
            详情
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            href={`/ai-chat/models/edit/${record.id}`}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个模型吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              loading={loading}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: 'AI模型管理',
        subTitle: '管理AI模型配置和定价',
      }}
    >
      <ProTable<AIModel>
           scroll={{x: 'max-content'}}
        headerTitle="AI模型列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            href="/ai-chat/models/create"
          >
            新建模型
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          try {
            await autoLoginInDev();
            const response = await apiClients.aiChat.aiChatModelsList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.name, // 搜索参数
              provider: params.provider_name, // 过滤参数
              isActive: params.is_active, // 过滤参数
              ordering: sort && Object.keys(sort).length > 0 ?
                Object.entries(sort).map(([key, value]) => value === 'ascend' ? key : `-${key}`).join(',') :
                undefined, // 排序参数
            });
            return {
              data: response.data?.items || [],
              success: true,
              total: response.data?.total || 0
            };
          } catch (error) {
            message.error('获取数据失败');
            return { data: [], success: false, total: 0 };
          }
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default AIModelList;
